package laserdancer.smart.com.criminalintent;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TimePicker;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Created by ares on 2018/2/5.
 */

public class DatePickerFragment extends DialogFragment {

    private static final String ARG_DATE = "DATE";
    public static final String EXTRA_DATE = "criminalintent.DATE";

    private DatePicker mDatePicker;
    private Date mDate;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){
        mDate = (Date) getArguments().getSerializable(ARG_DATE);

        Calendar _calendar = Calendar.getInstance();
        _calendar.setTime(mDate);
        int year = _calendar.get(Calendar.YEAR);
        int month = _calendar.get(Calendar.MONTH);
        int day = _calendar.get(Calendar.DAY_OF_MONTH);


        View _v = LayoutInflater.from(getActivity()).inflate(R.layout.datedialog,null);
        mDatePicker = _v.findViewById(R.id.dialog_date_datePicker);

        mDatePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                mDate = new GregorianCalendar(year,monthOfYear,dayOfMonth).getTime();
                getArguments().putSerializable(EXTRA_DATE,mDate);
            }
        });

        //TimePicker _timePicker =new TimePicker(getActivity());
        return new AlertDialog.Builder(getActivity())
                .setTitle("日期选择器")
                .setView(mDatePicker)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sendResult(Activity.RESULT_OK);
                    }
                })
                .create();
    }

    private void sendResult(int resultCode){
        if(getTargetFragment() == null){
            return;
        }

        Intent i = new Intent();
        i.putExtra(EXTRA_DATE,mDate);

        getTargetFragment().onActivityResult(getTargetRequestCode(),resultCode,i);
    }

    public static DatePickerFragment newInstance(Date _date){
        Bundle args = new Bundle();
        args.putSerializable(ARG_DATE,_date);

        DatePickerFragment _fragment = new DatePickerFragment();
        _fragment.setArguments(args);
        return _fragment;
    }

}
